import { Component, OnInit, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
import { ConfigService } from '../../../core/common/config.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { SelectComponent } from '../../../shared/component/ng2-select/select';
import swal from 'sweetalert2';
import { CommonService } from '../../../core/common/common.service';
@Component({
      selector: 'app-accountmanage',
      templateUrl: './accountmanage.component.html',
      styleUrls: ['./accountmanage.component.scss']
})
export class AccountmanageComponent implements OnInit {
      @ViewChild('addaccountForm') public addaccountForm;
      @ViewChild('addaccount') public addaccount: ModalDirective;
      @ViewChild('addaccountSelect') public addaccountSelect: SelectComponent;
      @ViewChild('channelSelect') public channelSelect: SelectComponent;
      @ViewChild('channelGroupSelect') public channelGroupSelect: SelectComponent;
      @ViewChild('custSelect') public custSelect: SelectComponent;
      @ViewChild('custGroupSelect') public custGroupSelect: SelectComponent;
      public system: any;
      public channel: any;
      public user: any;
      public addacc: any = {
            'userId': '',
            'system': '',
            'accounts': '',
            'name': '',
            'email': '',
            'emailError': '',
            'accountError': '',
            'mobile': '',
            'telephone': '',
            'remark': '',
            'authorityType': '',
            'able': true,
            'isadd': '1',

            'channel': '',
            'channelGroup': '',

            'cust': '',
            'custGroup': ''
      };
      public judge = true;
      public selectedSystem: any;
      public selectedChannel: any;
      public selectedUser: any;
      public judgeThree = '0';
      constructor(public configService: ConfigService, public http: Http, public activatedRoute: ActivatedRoute, 
            public router: Router, public commonService: CommonService) {
      }
      ngOnInit() {
            this.initSystem();
            this.initChannel();
            this.initUser();
            this.initSelectAuthority();
      }
      public initSystem(): void {
            const url = this.configService.get('url') + '?service=SaleService&method=getChnlSales';
            this.http.post(url, { 'chnlId': '1' }).toPromise().then(data => {
                  // console.log(data);
                  if (data.json().code === '0000') {
                        this.system = data.json().info;
                        // console.log(this.system);
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public initChannel(): void {
            const url = this.configService.get('url') + '?service=SaleService&method=getAllChnlSales';
            this.http.post(url, { 'chnlId': '1' }).toPromise().then(data => {
                  // console.log(data);
                  if (data.json().code === '0000') {
                        // console.log(data.json());
                        this.channel = data.json().info;
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public initUser() {
            const url = this.configService.get('url') + '?service=CustUserService&method=getAllCustUserList';
            this.http.post(url, null).toPromise().then((data: any) => {
                  if (data.json().code === '0000') {
                        // console.log(data.json());
                        this.user = data.json().info;
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public addBtn() {
            // console.log(this.addacc.able);
            if (this.judgeThree === '1') {
                  this.chnlSelected();
            }else if (this.judgeThree === '2') {
                  this.custSelected();
            }
            this.addacc.isadd = '1';
            this.addaccountForm.reset();
            this.addacc.emailError = '';
            this.addacc.accountError = '';
      }
      public updateBtn() {
            if (this.selectedSystem !== undefined || this.selectedChannel !== undefined || this.selectedUser !== undefined) {
                  // console.log(this.selectedSystem);
                  for (const item of this.addacc) {
                        this.addacc[item] = '';
                  }
                  // console.log(this.addacc);
                  this.addacc.able = false;
                  this.addacc.isadd = '2';
                  // console.log(this.addacc);
                  this.addacc.emailError = '';
                  this.addacc.accountError = '';
                  this.addaccount.show();
                  let three: any;
                  if ( this.judgeThree === '0') {
                        three = this.selectedSystem;
                        this.addacc.name = three.name;
                  }else if ( this.judgeThree === '1') {
                        // this.channelSelect.items = [];
                        this.channelGroupSelect.items = undefined;
                        three = this.selectedChannel;
                        this.chnlSelected();
                        this.addacc.name = three.name;
                        this.addacc.channel = three.chnlId;
                        // this.channelGroupSelected(three.chnlId);
                        this.addacc.channelGroup = three.groupId;
                  }else {
                        this.custGroupSelect.items = undefined;
                        three = this.selectedUser;
                        console.log(three);
                        this.custSelected();
                        this.addacc.name = three.userName;
                        this.addacc.cust = three.custId;
                        // this.custGroupSelected(three.custId);
                        if (three.areaId) {
                              this.addacc.custGroup = three.areaId;
                        }else {
                              this.addacc.custGroup = '-1';
                        }
                  }
                  this.addacc.accounts = three.account;
                  this.addacc.email = three.email;
                  this.addacc.mobile = three.mobile;
                  this.addacc.telephone = three.telephone;
                  this.addacc.remark = three.remark;
                  this.addacc.authorityType = three.userType;
                  this.addacc.userId = three.userId;
                  // console.log(this.addacc);
            } else {
                  swal('请选择帐号', '', 'error').catch(swal.noop);
            }
      }
      public changeEmail(value) {
            if (/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.exec(value)) {
                  this.addacc.emailError = '';
                  this.addacc.able = false;
            } else {
                  this.addacc.emailError = '邮箱格式不正确';
                  this.addacc.able = true;
            }
      }
      public initSelectAuthority() {
            let userType = '';
            if ( this.judgeThree === '0') {
                  userType = 'USER_TYPE_1';
            }else if ( this.judgeThree === '1') {
                  userType = 'USER_TYPE_2';
            }else {
                  userType = 'USER_TYPE_3';
            }
            const url = this.configService.get('url') + '?service=TableDictService&method=getDictList';
            this.http.post(url, { 'code': userType }).toPromise().then((data: any) => {
                  if (data.json().code === '0000') {
                        const accSelect = [];
                        // console.log(data.json().info);
                        data.json().info.forEach(item => {
                              accSelect.push({ id: item.value, text: item.label });
                        });
                        this.addaccountSelect.items = accSelect;
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public query() {
            let url;
            let message;
            const url_add = this.configService.get('url') + '?service=UserService&method=addUser';
            const url_update = this.configService.get('url') + '?service=UserService&method=updateUserInfo';
            const allinfo: any = {
                  'account': this.addacc.accounts,
                  'name': this.addacc.name,
                  'email': this.addacc.email,
                  'mobile': this.addacc.mobile,
                  'telephone': this.addacc.telephone,
                  'remark': this.addacc.remark,
                  'userType': this.addacc.authorityType
                  // 'chnlId': '1',
            };
            if (this.addacc.isadd === '1') {
                  url = url_add;
                  message = '添加成功';
            } else {
                  url = url_update;
                  message = '修改成功';
                  allinfo.userId = this.addacc.userId;
            }

            if ( this.judgeThree === '0') {
                  allinfo.chnlId = '1';
            }else if ( this.judgeThree === '1') {
                  allinfo.chnlId = this.addacc.channelGroup;
                  // console.log(this.selectedChannel.chnlId);
                  if (this.addacc.isadd === '2' && this.addacc.channelGroup !== this.selectedChannel.groupId) {
                        allinfo.oldChnlId = this.selectedChannel.groupId;
                  }
            }else {
                  allinfo.custId = this.addacc.cust;
                  if ( this.addacc.custGroup !== '-1') {
                        allinfo.areaId = this.addacc.custGroup;
                        if (this.addacc.isadd === '2' && this.addacc.custGroup !== this.selectedUser.areaId) {
                              allinfo.oldAreaId = this.selectedUser.areaId;
                              // console.log(this.selectedUser.areaId);
                              if (this.selectedUser.areaId === undefined) {
                                    allinfo.oldAreaId = '';
                              }
                        }
                  }else if ( this.addacc.custGroup === '-1') {
                        if (this.addacc.isadd === '2' &&  this.selectedUser.areaId) {
                              allinfo.areaId = '';
                              allinfo.oldAreaId = this.selectedUser.areaId;
                        }
                  }
            }
            // console.log(allinfo);
            this.http.post(url, allinfo

            ).toPromise().then(data => {
                  if (data.json().code === '0000') {
                        swal({
                              title: message,
                              type: 'success',
                              confirmButtonColor: '#3085d6',
                              confirmButtonText: '确定',
                              confirmButtonClass: 'btn btn-success',
                        }).then((e: any) => {
                              this.addaccount.hide();
                              if ( this.judgeThree === '0') {
                                    this.initSystem();
                              }else if ( this.judgeThree === '1') {
                                    this.initChannel();
                              }else {
                                    this.initUser();
                              }
                        }, (dismiss: any) => {
                              this.addaccount.hide();
                              if ( this.judgeThree === '0') {
                                    this.initSystem();
                              }else if ( this.judgeThree === '1') {
                                    this.initChannel();
                              }else {
                                    this.initUser();
                              }
                        }).then(() => {
                              this.selectedSystem = undefined;
                              this.selectedChannel = undefined;
                              this.selectedUser = undefined;
                        });
                  } else {
                        console.log(data.json().message);
                        // this.addaccount.hide();
                  }
            });
      }
      public changeState(val) {
            // console.log(this.selectedSystem);
            let action;
            if (val === 1) {
                  action = 'frozen';
            } else {
                  action = 'activate';
            }
            if (this.selectedSystem !== undefined || this.selectedChannel !== undefined || this.selectedUser !== undefined) {
                  let three: any;
                  if ( this.judgeThree === '0') {
                        three = this.selectedSystem;
                  }else if ( this.judgeThree === '1') {
                        three = this.selectedChannel;
                  }else {
                        three = this.selectedUser;
                  }
                  const url = this.configService.get('url') + '?service=UserService&method=changeUserState';
                  this.http.post(url, { action: action, userIds: [{ userId: three.userId}] }).toPromise().then((data: any) => {
                        if (data.json().code === '0000') {
                              // console.log(data.json());
                              this.initSystem();
                              this.initChannel();
                              this.initUser();
                              this.selectedSystem = undefined;
                              this.selectedChannel = undefined;
                              this.selectedUser = undefined;
                        } else {
                              console.log(data.json().message);
                        }
                  });
            } else {
                  swal('请选择帐号', '', 'error').catch(swal.noop);
            }
      }
      public resetPwd() {
            if (this.selectedSystem !== undefined || this.selectedChannel !== undefined || this.selectedUser !== undefined) {
                  let three: any;
                  if ( this.judgeThree === '0') {
                        three = this.selectedSystem;
                  }else if ( this.judgeThree === '1') {
                        three = this.selectedChannel;
                  }else {
                        three = this.selectedUser;
                  }
                  swal({
                        title: '确认重置密码？',
                        type: 'warning',
                        showCancelButton: true,
                        cancelButtonText: '取消!',
                        confirmButtonColor: '#4C91EA',
                        confirmButtonText: '确定!'
                  }).then(() => {
                        const url = this.configService.get('url') + '?service=UserService&method=resetUserPwd';
                        this.http.post(url, { account: three.account }).toPromise().then((data: any) => {
                              // console.log(data);
                              if (data.json().code === '0000') {
                                    // console.log(data.json());
                                    swal('重置成功', '', 'success').catch(swal.noop).then(() => {
                                          this.selectedSystem = undefined;
                                          this.selectedChannel = undefined;
                                          this.selectedUser = undefined;
                                    });
                              } else {
                                    console.log(data.json().message);
                                    swal('警告！', data.json().message, 'warning').catch(swal.noop);
                              }
                        });
                  });
            } else {
                  swal('请选择帐号', '', 'error').catch(swal.noop);
            }
      }
      public destroy() {
            if (this.selectedSystem !== undefined || this.selectedChannel !== undefined || this.selectedUser !== undefined) {
                  let three: any;
                  if ( this.judgeThree === '0') {
                        three = this.selectedSystem;
                  }else if ( this.judgeThree === '1') {
                        three = this.selectedChannel;
                  }else {
                        three = this.selectedUser;
                  }
                  swal({
                        title: '确认删除？',
                        type: 'warning',
                        showCancelButton: true,
                        cancelButtonText: '取消!',
                        confirmButtonColor: '#4C91EA',
                        confirmButtonText: '确定!'
                  }).then(() => {
                        const url = this.configService.get('url') + '?service=UserService&method=DestoryUser';
                        this.http.post(url, { userId: three.userId }).toPromise().then((data: any) => {
                              // console.log(data);
                              if (data.json().code === '0000') {
                                    // console.log(data.json());
                                    swal('删除成功', '', 'success').catch(swal.noop).then(() => {
                                          this.selectedSystem = undefined;
                                          this.selectedChannel = undefined;
                                          this.selectedUser = undefined;
                                    });
                                    this.initSystem();
                                    this.initChannel();
                                    this.initUser();
                              } else {
                                    console.log(data.json().message);
                              }
                        });
                  });
            } else {
                  swal('请选择帐号', '', 'error').catch(swal.noop);
            }
      }
      public judgeAccount(val) {
            // console.log(val);
            const url = this.configService.get('url') + '?service=UserService&method=checkUserName';
            this.http.post(url, { 'account': val }).toPromise().then((data: any) => {
                  // console.log(data.json());
                  if (data.json().code === '0000') {
                        if (data.json().info === true) {
                              this.addacc.accountError = '';
                              this.judge = false;
                        } else {
                              this.addacc.accountError = '帐号已存在';
                              this.judge = true;
                        }
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public onTabChange($event) {
            // console.log(JSON.stringify($event));
            if ($event.index === 0) {
                  this.judgeThree = '0';
                  this.selectedChannel = undefined;
                  this.selectedUser = undefined;
                  this.initSelectAuthority();
            }else if ($event.index === 1) {
                  this.judgeThree = '1';
                  this.selectedSystem = undefined;
                  this.selectedUser = undefined;
                  this.initSelectAuthority();
            }else {
                  this.judgeThree = '2';
                  this.selectedSystem = undefined;
                  this.selectedChannel = undefined;
                  this.initSelectAuthority();
            }
      }
      public chnlSelected() {
            const url = this.configService.get('url') + '?service=ChnlService&method=getChnlList';
            this.http.post(url, null).toPromise().then((data: any) => {
                  if (data.json().code === '0000') {
                        const chnl = [];
                        // console.log(data.json().info);
                        data.json().info.forEach(item => {
                              chnl.push({ id: item.chnlId, text: item.chnlName });
                              // console.log(item.chnlId);
                        });
                        this.channelSelect.items = chnl;
                        // console.log(chnl[0].id);
                        // this.commonService.setSelect(chnl[0].id, this.channelSelect, true);
                        // this.groupSelected(chnl[0]);
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public channelGroupSelected(val) {
            // console.log(val);
            const url = this.configService.get('url') + '?service=ChnlService&method=getChnlGroupList';
            this.http.post(url, {'chnlId': val.id}).toPromise().then((data: any) => {
                  if (data.json().code === '0000') {
                        const group = [];
                        // console.log(data.json().info);
                        data.json().info.forEach(item => {
                              group.push({ id: item.chnlId, text: item.chnlName });
                              // console.log(item.chnlId);
                        });
                        this.channelGroupSelect.items = group;
                        // this.commonService.setSelect(group[0].id, this.channelGroupSelect, true);
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public custSelected() {
            const url = this.configService.get('url') + '?service=QueryInfoService&method=getCustList';
            this.http.post(url, null).toPromise().then((data: any) => {
                  if (data.json().code === '0000') {
                        const cust = [];
                        // console.log(data.json().info);
                        data.json().info.forEach(item => {
                              cust.push({ id: item.custId, text: item.custName });
                              // console.log(item.chnlId);
                        });
                        this.custSelect.items = cust;
                        // console.log(cust);
                        // console.log(chnl[0].id);
                        // this.commonService.setSelect(cust[0].id, this.custSelect, true);
                        // this.groupSelected(chnl[0]);
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public custGroupSelected(val) {
            // console.log(val);
            const url = this.configService.get('url') + '?service=CustAreaService&method=getCustAreaList';
            this.http.post(url, {'custId': val.id}).toPromise().then((data: any) => {
                  if (data.json().code === '0000') {
                        console.log(data.json().info);
                        const group = [];
                        group.push({ id: '-1', text: '无分组' });
                        if ( data.json().info.length !== 0) {
                              data.json().info.forEach(item => {
                                    group.push({ id: item.areaId, text: item.areaName });
                                    // console.log(item.areaId);
                              });
                        }else {
                              this.custGroupSelect.items = group;
                              this.commonService.setSelect(group[0].id, this.custGroupSelect, true);
                        }
                        this.custGroupSelect.items = group;
                        console.log(this.custGroupSelect.items);
                  } else {
                        console.log(data.json().message);
                  }
            });
      }
      public onRowSelect(data): void {

      }
}
